package com.fm.common.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ToastUtils
import java.lang.Exception
import java.lang.reflect.ParameterizedType

/**
 *
 * @Author:         ly2
 * @CreateDate:     2020/12/18
 * @Description:    base fragment
 *
 */
abstract class BaseBPFragment<B : ViewBinding, P : BasePresenter<*>> : Fragment(), IView {
    protected var binding: B? = null

    protected var mPresenter: P? = null

    protected var mContext: Context? = null

    /**
     * 处理，fragment每次打开调用init data，获取数据，浪费资源
     */
    //是否每次打开fragment获取数据
    protected var mGetDataWhenShow = false

    //是否已经成功获取数据
    protected var mHasGetData = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = activity
        onLoadPresenter()?.let {
            mPresenter = it
            it.attachView(this)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        //初始化布局
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            try {
                @Suppress("UNCHECKED_CAST")
                val clzz: Class<B> = type.actualTypeArguments[0] as Class<B>
                val method = clzz.getMethod("inflate", LayoutInflater::class.java)
                @Suppress("UNCHECKED_CAST")
                binding = method.invoke(null, layoutInflater) as B
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return binding?.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()
        if (!mHasGetData || mGetDataWhenShow) {
            initData()
        }
    }

    abstract fun initView()

    open fun initData() {
    }

    open fun onLoadPresenter(): P? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        ToastUtils.cancel()
        binding = null
        mPresenter?.detachView()
    }

    override fun bindToLife(): LifecycleOwner {
        return this
    }
}